package com.slw.emergency.init;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.slw.emergency.constant.InitConstant;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.*;

@Configuration
public class CommandLineRunnerImpl implements CommandLineRunner {
    private static Logger logger = LoggerFactory.getLogger(CommandLineRunnerImpl.class);
    @Override
    public void run(String... args) throws Exception {
        String str = initLng();
        JSONArray jsonArray = JSONArray.parseArray(str);

        StringBuffer sb = new StringBuffer();
        sb.append("110000");
        sb.append("120000");
        sb.append("310000");
        sb.append("500000");
        sb.append("810000");
        sb.append("820000");

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name = jsonObject.getString("name");
            String adcode = jsonObject.getString("adcode");
            //4个直辖市 2个特别行政区
            if (sb.indexOf(adcode) !=-1){
                jsonObject.remove("districts");
                jsonObject.put("province",name);
                InitConstant.lngMap.put(adcode,jsonObject);
                continue;
            }

            JSONArray children = jsonObject.getJSONArray("districts");
            for (int j = 0; j<children.size();j++){
                JSONObject childrenObj = children.getJSONObject(j);
                String childCode = childrenObj.getString("adcode");
                childrenObj.remove("districts");
                childrenObj.put("province",name);
                childrenObj.put("city",childrenObj.getString("name"));
                InitConstant.lngMap.put(childCode,childrenObj);
            }
        }
    }

    /**
     * 解析本地json坐标文件
     * @return
     * @throws IOException
     */
    private String initLng() throws IOException {
        Resource resource = new ClassPathResource("templates/lng.json");
        InputStream is = resource.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String data = null;
        StringBuilder sb = new StringBuilder();
        while((data = br.readLine()) != null) {
           sb.append(data);
        }

        br.close();
        isr.close();
        is.close();

        return sb.toString();
    }
}
